package com.easylinkin.linkappapi.lobar.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.config.entity.Config;
import com.easylinkin.linkappapi.config.service.ConfigService;
import com.easylinkin.linkappapi.elasticsearch.entity.ESconfig;
import com.easylinkin.linkappapi.lobar.dto.LaborRegionDTO;
import com.easylinkin.linkappapi.lobar.dto.UserProjectDTO;
import com.easylinkin.linkappapi.lobar.dto.UserRecordDTO;
import com.easylinkin.linkappapi.lobar.dto.region.RegionDTO;
import com.easylinkin.linkappapi.lobar.dto.region.UserRegionDTO;
import com.easylinkin.linkappapi.lobar.dto.screen.LobarScreenDTO;
import com.easylinkin.linkappapi.lobar.entity.LaborRegion;
import com.easylinkin.linkappapi.lobar.entity.LobarSet;
import com.easylinkin.linkappapi.lobar.entity.UserProject;
import com.easylinkin.linkappapi.lobar.entity.UserRecord;
import com.easylinkin.linkappapi.lobar.mapper.LaborRegionMapper;
import com.easylinkin.linkappapi.lobar.mapper.UserProjectMapper;
import com.easylinkin.linkappapi.lobar.mapper.UserRecordMapper;
import com.easylinkin.linkappapi.lobar.service.LaborRegionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.lobar.service.LobarSetService;
import com.easylinkin.linkappapi.lobar.util.GaodeUtils;
import com.easylinkin.linkappapi.lobar.util.LobarUtils;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 区域坐标表 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Service
public class LaborRegionServiceImpl extends ServiceImpl<LaborRegionMapper, LaborRegion> implements LaborRegionService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;
  @Autowired
  private ESconfig eSconfig;
  @Autowired
  private UserProjectMapper userProjectMapper;
  @Autowired
  private ConfigService configService;
  @Autowired
  private LobarSetService lobarSetService;
  @Autowired
  private UserRecordMapper userRecordMapper;

  private String laborRegion = "labor_region";

  /**
   * 增加
   * @param laborRegionDTO
   */
  @Override
  public void insert(LaborRegionDTO laborRegionDTO) {
    LaborRegion laborRegion = BeanUtil.toBean(laborRegionDTO, LaborRegion.class);
    /**
     * 验证重复
     */
    this.checkExist(laborRegion);
    //设置基本属性
    this.setBase(laborRegion);
    //设置坐标json
    if (null != laborRegionDTO.getRegionDTOList() && laborRegionDTO.getRegionDTOList().size() > 0){
      String jsonStr = JSONUtil.toJsonStr(laborRegionDTO.getRegionDTOList());
      laborRegion.setCoordinate(jsonStr);
    }
    this.save(laborRegion);
  }

  /**
   * 根据id编辑
   * @param laborRegionDTO
   */
  @Override
  public void updateOne(LaborRegionDTO laborRegionDTO) {
    LaborRegion laborRegion = BeanUtil.toBean(laborRegionDTO, LaborRegion.class);
    /**
     * 验证重复
     */
    this.checkExist(laborRegion);
    //设置基本属性
    this.setBase(laborRegion);
    //设置坐标json
    if (null != laborRegionDTO.getRegionDTOList() && laborRegionDTO.getRegionDTOList().size() > 0){
      String jsonStr = JSONUtil.toJsonStr(laborRegionDTO.getRegionDTOList());
      laborRegion.setCoordinate(jsonStr);
    }
    this.updateById(laborRegion);
  }

  @Override
  public LaborRegionDTO findById(Long id) {
    LaborRegion laborRegion = baseMapper.selectById(id);
    LaborRegionDTO laborRegionDTO = BeanUtil.toBean(laborRegion, LaborRegionDTO.class);
    //String转json
    if (StringUtils.isNotBlank(laborRegion.getCoordinate())){
      List<RegionDTO> regionDTOS = JSONUtil.toList(laborRegion.getCoordinate(), RegionDTO.class);
      laborRegionDTO.setRegionDTOList(regionDTOS);
    }
    return laborRegionDTO;
  }

  /**
   * 在场人数(施工区,办公区,生活区)
   * @param userWorkType 人员类型 1:作业人员 2:管理人员
   */
  @Override
  public List<LobarScreenDTO> onNum(Integer userWorkType) throws IOException {
    List<LobarScreenDTO> lobarScreenDTOS = new ArrayList<>();
    LobarScreenDTO lobarScreenDTO1 = new LobarScreenDTO();
    lobarScreenDTO1.setName("施工区");
    LobarScreenDTO lobarScreenDTO2 = new LobarScreenDTO();
    lobarScreenDTO2.setName("办公区");
    LobarScreenDTO lobarScreenDTO3 = new LobarScreenDTO();
    lobarScreenDTO3.setName("生活区");
    lobarScreenDTOS.add(lobarScreenDTO1);lobarScreenDTOS.add(lobarScreenDTO2);
    lobarScreenDTOS.add(lobarScreenDTO3);
    //查询该项目属于哪种考勤在场判断
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    LobarSet lobarSet = lobarSetService.getByTenantId(tenantId);
    String showArea = lobarSet.getShowArea();
    if(StringUtils.isEmpty(showArea)){
      return null;
    }
    Integer allType = lobarSet.getAllType();
    List<String> buildTypes = null;
    if (Integer.valueOf(2).equals(allType)){
      //分包
      Config typeConfig = configService.getOneByKey("LABOUR_BIG_SCREEN_LABOUR_COMPANY_TYPE");
      if(typeConfig!=null){
        String value = typeConfig.getValue();
        if(StringUtils.isNotBlank(value)){
          buildTypes = JSONUtil.toList(value,String.class);
        }
      }
    }
    if (Integer.valueOf(1).equals(lobarSet.getOnType())){
      //查询库里面的区域坐标
      List<LaborRegionDTO> laborRegionDTOS = this.queryList();
      //查询人员坐标
      //判断人员在不在项目,在不在场
      List<UserRegionDTO> regions = this.getRegions();
      //根据人员类型过滤
      if (Integer.valueOf(1).equals(userWorkType)){
        /**
         * 工种类别
         * 黄点：花名册的作业人员 1
         * 白点：花名册中的管理人员 2
         * 红点：花名册的其他人员 3
         */
        regions.removeIf(u->Integer.valueOf(2).equals(u.getType()));
      }else if (Integer.valueOf(2).equals(userWorkType)){
        regions.removeIf(u->!Integer.valueOf(2).equals(u.getType()));
      }
      regions.removeIf(u->!u.isOnLine());
//      if (null != buildTypes){
//        List<String> finalBuildTypes = buildTypes;
//        regions.removeIf(r ->!finalBuildTypes.contains(r.getBuildType()));
//      }
      //过滤分包
      //获取数量
      getNum(lobarScreenDTOS, laborRegionDTOS, regions);
    }else {
      //实名制道闸
//      List<UserRecord> userRecords = userRecordMapper.getOnAreaToDay(tenantId,buildTypes);
      List<UserProjectDTO> userProjectList = userProjectMapper.getOnArea(tenantId,buildTypes);
      //按照人员类型过滤
      if (Integer.valueOf(1).equals(userWorkType)){
        userProjectList.removeIf(u-> LobarUtils.isManager(u.getWorkType()));
      }else if (Integer.valueOf(2).equals(userWorkType)){
        userProjectList.removeIf(u-> !LobarUtils.isManager(u.getWorkType()));
      }
      //过滤分包
      //1施工区
      List<String> userIds1 = userProjectList.stream().filter(u -> Integer.valueOf(1).equals(u.getOnArea()))
              .map(UserProject::getUserId).collect(Collectors.toList());
      //2办公区
      List<String> userIds2 = userProjectList.stream().filter(u -> Integer.valueOf(2).equals(u.getOnArea()))
              .map(UserProject::getUserId).collect(Collectors.toList());
      //3生活区
      List<String> userIds3 = userProjectList.stream().filter(u -> Integer.valueOf(3).equals(u.getOnArea()))
          .map(UserProject::getUserId).collect(Collectors.toList());
      lobarScreenDTOS.get(0).setNum(userIds1.size());
      lobarScreenDTOS.get(0).setUserIds(userIds1);
      lobarScreenDTOS.get(1).setNum(userIds2.size());
      lobarScreenDTOS.get(1).setUserIds(userIds2);
      lobarScreenDTOS.get(2).setNum(userIds3.size());
      lobarScreenDTOS.get(2).setUserIds(userIds3);
    }
    List<Integer> showAreaList = Arrays.asList(showArea.split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
    // 结果集
    List<LobarScreenDTO> resultShowAreaList = new ArrayList<>();
    showAreaList.forEach(p->resultShowAreaList.add(lobarScreenDTOS.get(p-1)));
    return resultShowAreaList;
  }

//  private List<UserRecord> getUserRecords(String tenantId) {
//    List<Integer> list = new ArrayList<>();
////      前区域：1施工区，2办公区，3生活区,4项目外
//    list.add(1);
//    list.add(2);
//    list.add(3);
//    Date date = new Date();
//    QueryWrapper<UserRecord> queryWrapper = new QueryWrapper<>();
//    queryWrapper.eq("tenant_id_",tenantId)
//        .ge("record_time_", DateUtil.beginOfDay(date))
//        .le("record_time_",DateUtil.endOfDay(date))
//        .in("on_area_",list);
//    return userRecordMapper.selectList(queryWrapper);
//  }

  /**
   * 获取数量
   * @param lobarScreenDTOS
   * @param laborRegionDTOS
   * @param regionDTOS
   */
  private void getNum(List<LobarScreenDTO> lobarScreenDTOS, List<LaborRegionDTO> laborRegionDTOS,
      List<UserRegionDTO> regionDTOS) {
    //施工区人员
    AtomicInteger i1 = new AtomicInteger();
    List<String> userIds1 = new ArrayList<>();
    //生活区人员
    AtomicInteger i2 = new AtomicInteger();
    List<String> userIds2 = new ArrayList<>();
    //办公区人员
    AtomicInteger i3 = new AtomicInteger();
    List<String> userIds3 = new ArrayList<>();
    laborRegionDTOS.forEach(r->{
      if (Integer.valueOf(1).equals(r.getType())){
        regionDTOS.forEach(re->{
          boolean b = GaodeUtils
              .isPtInPoly(re.getPositionX(), re.getPositionY(), r.getRegionDTOList());
          if (b){
            i1.getAndIncrement();
            userIds1.add(re.getBaseUserId());
          }
        });
      }else if (Integer.valueOf(2).equals(r.getType())){
        regionDTOS.forEach(re->{
          boolean b = GaodeUtils
              .isPtInPoly(re.getPositionX(), re.getPositionY(), r.getRegionDTOList());
          if (b){
            i2.getAndIncrement();
            userIds2.add(re.getBaseUserId());
          }
        });
      }else if (Integer.valueOf(3).equals(r.getType())){
        regionDTOS.forEach(re->{
          boolean b = GaodeUtils
              .isPtInPoly(re.getPositionX(), re.getPositionY(), r.getRegionDTOList());
          if (b){
            i3.getAndIncrement();
            userIds3.add(re.getBaseUserId());
          }
        });
      }
    });
    lobarScreenDTOS.get(0).setNum(i1.get());
    lobarScreenDTOS.get(0).setUserIds(userIds1);
    lobarScreenDTOS.get(1).setNum(i2.get());
    lobarScreenDTOS.get(1).setUserIds(userIds2);
    lobarScreenDTOS.get(2).setNum(i3.get());
    lobarScreenDTOS.get(2).setUserIds(userIds3);
  }

  /**
   * 人员分类统计
   * type有值表示需要过滤，取分包单位数据
   */
  @Override
  public Map<String,List<LobarScreenDTO>> groupNum(Integer userWorkType) throws IOException {
    Map<String,List<LobarScreenDTO>> map = new HashMap<>();
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    //查询全部在场人员
    List<UserProjectDTO> userProjectDTOS = userProjectMapper.findByTenantId(tenantId);
    //过滤人员类型
    if (Integer.valueOf(1).equals(userWorkType)){
      userProjectDTOS.removeIf(u-> LobarUtils.isManager(u.getWorkType()));
    }else if (Integer.valueOf(2).equals(userWorkType)){
      userProjectDTOS.removeIf(u->!LobarUtils.isManager(u.getWorkType()));
    }
    //查询设置
    LobarSet lobarSet = lobarSetService.getByTenantId(tenantId);
    Integer allType = lobarSet.getAllType();
    if (Integer.valueOf(2).equals(allType)){
      //分包
      Config typeConfig = configService
          .getOneByKey("LABOUR_BIG_SCREEN_LABOUR_COMPANY_TYPE");
      if(typeConfig!=null){
        String value = typeConfig.getValue();
        if(StringUtils.isNotBlank(value)){
          JSONArray jsonArray = JSONUtil.parseArray(value);
          //过滤掉非专业单位和分包单位的
          userProjectDTOS.removeIf(u-> !jsonArray.contains(u.getBuildType()));
        }
      }
    }
    if (Integer.valueOf(1).equals(lobarSet.getOnType())){
      //定位
      //获取es中的打卡人员
      List<UserRegionDTO> userRegionDTOList = getFromEs();
      //求人员是否在场
      userProjectDTOS.forEach(u->{
        List<UserRegionDTO> dtoList = userRegionDTOList.stream()
            .filter(user -> u.getUserId().equals(user.getBaseUserId()))
            .collect(Collectors.toList());
        if (dtoList.size()>0){
          u.setOnLine(dtoList.get(0).isOnLine());
        }
      });
    }else {
      //道闸
//      List<UserRecord> userRecords = getUserRecords(tenantId);
      //求人员是否在场
      userProjectDTOS.forEach(u->{
        if (null != u.getOnArea() && !Integer.valueOf(4).equals(u.getOnArea())){
          u.setOnLine(true);
        }
      });
    }
    //增加一个管理人员工种的
    Map<String, List<UserProjectDTO>> manageMap = userProjectDTOS.stream()
            .filter(u-> StringUtils.isNotBlank(u.getWorkType()) && LobarUtils.isManager(u.getWorkType()))
            .collect(Collectors.groupingBy(u -> u.getWorkType().substring(u.getWorkType().lastIndexOf("/") + 1)));
    map.put("管理人员",getByMap(manageMap,3));
    //按单位统计
    Map<String, List<UserProjectDTO>> companyMap = userProjectDTOS.stream()
        .collect(Collectors.groupingBy(UserProjectDTO::getCompanyProjectId));
    map.put("单位",getByMap(companyMap,1));
    //按班组统计
    Map<String, List<UserProjectDTO>> groupMap = userProjectDTOS.stream()
        .collect(Collectors.groupingBy(UserProjectDTO::getGroupId));
    map.put("班组",getByMap(groupMap,2));
    //按工种统计
    Map<String, List<UserProjectDTO>> workTypeMap = userProjectDTOS.stream().filter(u-> StringUtils.isNotBlank(u.getWorkType())).collect(Collectors
        .groupingBy(u -> u.getWorkType().substring(u.getWorkType().lastIndexOf("/") + 1)));
    map.put("工种",getByMap(workTypeMap,3));
    return map;
  }

  /**
   * 分组统计数据
   * @param companyMap
   */
  private List<LobarScreenDTO> getByMap(Map<String, List<UserProjectDTO>> companyMap,int type) {
    List<LobarScreenDTO> lobarScreenDTOS = new ArrayList<>();
    companyMap.forEach((k,v)->{
      LobarScreenDTO lobarScreenDTO;
      if (type == 1){
        lobarScreenDTO = new LobarScreenDTO(v.get(0).getCompanyName(),v.stream().map(UserProjectDTO::getUserId).collect(Collectors.toList()),v.get(0).getAbbreviation());
      }else if (type == 2){
        lobarScreenDTO = new LobarScreenDTO(v.get(0).getGroupName(),v.stream().map(UserProjectDTO::getUserId).collect(Collectors.toList()),v.get(0).getAbbreviation());
      }else {
        lobarScreenDTO = new LobarScreenDTO(k,v.stream().map(UserProjectDTO::getUserId).collect(Collectors.toList()));
      }
      //在场人数统计
      List<String> userIds = v.stream().filter(UserProjectDTO::isOnLine).map(UserProjectDTO::getUserId).collect(Collectors.toList());
      lobarScreenDTO.setIn(userIds.size());
      lobarScreenDTO.setInUserIds(userIds);
      lobarScreenDTOS.add(lobarScreenDTO);
    });
    return lobarScreenDTOS.stream().sorted(Comparator.comparing(LobarScreenDTO::getNum).reversed()).collect(Collectors.toList());
  }

  /**
   * 从es获取人员并组织数据
   * @return
   * @throws IOException
   */
  private List<UserRegionDTO> getFromEs() throws IOException {
    List<UserRegionDTO> userRegionDTOS = this.getUserRegionFromEs();
    if (userRegionDTOS.size() > 0){
      List<Long> ids = userRegionDTOS.stream().map(u -> u.getUserId())
          .collect(Collectors.toList());
      List<UserRegionDTO> newUserRegions = userProjectMapper.findUserRByIds(userRegionDTOS.get(0).getTenantId(),ids);
      userRegionDTOS.forEach(u->{
        List<UserRegionDTO> dtos = newUserRegions.stream()
            .filter(n -> n.getUserId().equals(u.getUserId())).collect(Collectors.toList());
        if (dtos.size() > 0){
          //获取姓名工种班组单位更新时间
          UserRegionDTO userRegionDTO = dtos.get(0);
          u.setBaseUserId(userRegionDTO.getBaseUserId());
        }
      });
    }
    //获取区域坐标
    List<LaborRegionDTO> regionDTOS = this.queryList();
//    List<LaborRegionDTO> regionDTOS = laborRegionDTOS.stream()
//        .filter(l -> Integer.valueOf(1).equals(l.getType())).collect(Collectors.toList());
    //判断是否在施工区
    userRegionDTOS.forEach(u->{
      if (regionDTOS.size() > 0){
        for (int i = 0; i <regionDTOS.size(); i++) {
          LaborRegionDTO regionDTO = regionDTOS.get(i);
          boolean ptInPoly = GaodeUtils
              .isPtInPoly(u.getPositionX(), u.getPositionY(), regionDTO.getRegionDTOList());
          if (ptInPoly){
            u.setOnLine(true);
            break;
          }
        }
      }
    });
    return userRegionDTOS;
  }

  /**
   * 人员坐标上传
   */
  @Override
  public void insertRegion(UserRegionDTO userRegionDTO) throws IOException {
    RestHighLevelClient rhlClient = eSconfig.getRHLClient();
    GetIndexRequest indexRequest = new GetIndexRequest().indices(this.laborRegion);
    boolean exists = rhlClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
    if (!exists){
      //创建索引
      CreateIndexRequest createIndexRequest = new CreateIndexRequest(this.laborRegion);
      rhlClient.indices().create(createIndexRequest,RequestOptions.DEFAULT);
    }
    //保存数据到es
    if (null == userRegionDTO.getUserId()){
      userRegionDTO.setUserId(linkappUserContextProducer.getCurrent().getId());
    }
    if (StringUtils.isBlank(userRegionDTO.getTenantId())){
      userRegionDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
    if (null == userRegionDTO.getTime()){
      userRegionDTO.setTime(new Date());
    }
    IndexRequest request = new IndexRequest(this.laborRegion,"type");
    // 设置文档id
    request.id(userRegionDTO.getUserId()+"-"+userRegionDTO.getTime().getTime());
    // 将json格式字符串放在请求中
    request.source(JSONObject.toJSONString(userRegionDTO), XContentType.JSON);
    rhlClient.index(request,RequestOptions.DEFAULT);
  }

  /**
   * 人员坐标获取
   */
  @Override
  public List<UserRegionDTO> getRegions() throws IOException {
    List<UserRegionDTO> userRegionDTOS = new ArrayList<>();
    //判断是道闸但是人员定位
    //查询该项目属于哪种考勤在场判断
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    LobarSet lobarSet = lobarSetService.getByTenantId(tenantId);
    if (Integer.valueOf(1).equals(lobarSet.getOnType())){
      //查询该项目属于哪种考勤在场判断
      Integer allType = lobarSet.getAllType();
      List<String> buildTypes = new ArrayList<>();
      if (Integer.valueOf(2).equals(allType)){
        //分包
        Config typeConfig = configService.getOneByKey("LABOUR_BIG_SCREEN_LABOUR_COMPANY_TYPE");
        if(typeConfig!=null){
          String value = typeConfig.getValue();
          if(StringUtils.isNotBlank(value)){
            buildTypes = JSONUtil.toList(value,String.class);
          }
        }
      }

      //获取es最近5分钟的数据
      userRegionDTOS = getUserRegionFromEs();
      //组织数据
      if (userRegionDTOS.size() > 0){
        List<Long> ids = userRegionDTOS.stream().map(u -> u.getUserId())
            .collect(Collectors.toList());
        List<UserRegionDTO> newUserRegions = userProjectMapper.findUserRegionByIds(userRegionDTOS.get(0).getTenantId(),ids);
        List<String> finalBuildTypes = buildTypes;
        if (finalBuildTypes.size() > 0){
          newUserRegions.removeIf(n->!finalBuildTypes.contains(n.getBuildType()));
        }
        userRegionDTOS.forEach(u->{
          List<UserRegionDTO> dtos = newUserRegions.stream()
              .filter(n -> n.getUserId().equals(u.getUserId())).collect(Collectors.toList());
          if (dtos.size() > 0){
            //获取姓名工种班组单位更新时间
            UserRegionDTO userRegionDTO = dtos.get(0);
            u.setUserName(userRegionDTO.getUserName());
            u.setWorkType(userRegionDTO.getWorkType());
            u.setGroupName(userRegionDTO.getGroupName());
            u.setCompanyName(userRegionDTO.getCompanyName());
            //判断是哪个颜色
//          黄点：花名册的作业人员   1
//          白点：花名册中的管理人员 2
//          红点：花名册的其他人员 3
            String workType = u.getWorkType();
            if (StringUtils.isNotBlank(workType)){
              if (workType.startsWith("作业人员")){
                u.setType(1);
              }else if (workType.startsWith("管理人员")){
                u.setType(2);
              }else {
                u.setType(3);
              }
            }
          }
        });
      }
      userRegionDTOS.removeIf(u->StringUtils.isBlank(u.getUserName()));
      //获取区域坐标
      List<LaborRegionDTO> regionDTOS = this.queryList();
      //判断是否在施工区
      userRegionDTOS.forEach(u->{
        if (regionDTOS.size() > 0){
          for (int i = 0; i <regionDTOS.size(); i++) {
            LaborRegionDTO regionDTO = regionDTOS.get(i);
            boolean ptInPoly = GaodeUtils
                .isPtInPoly(u.getPositionX(), u.getPositionY(), regionDTO.getRegionDTOList());
            if (ptInPoly){
              u.setOnLine(true);
              break;
            }
          }
        }
      });
//      userRegionDTOS.removeIf(u->!u.isOnLine());
    }
    return userRegionDTOS;
  }

  @Override
  public List<LaborRegionDTO> queryList() {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    LobarSet lobarSet = lobarSetService.getByTenantId(tenantId);
    String showArea = lobarSet.getShowArea();
    if(StringUtils.isEmpty(showArea)){
      return null;
    }
    QueryWrapper<LaborRegion> queryWrapper = new QueryWrapper<>();
    List<Integer> list = Arrays.asList(showArea.split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
//    List<Integer> list = new ArrayList<>();
//    list.add(1);list.add(2);list.add(3);
    queryWrapper.eq("tenant_id_",tenantId).in("type_",list);
    List<LaborRegion> laborRegions = baseMapper.selectList(queryWrapper);
    List<LaborRegionDTO> laborRegionDTOS = BeanUtil.copyToList(laborRegions, LaborRegionDTO.class);
    laborRegionDTOS.forEach(l->{
      if (StringUtils.isNotBlank(l.getCoordinate())){
        List<RegionDTO> regionDTOS = JSONUtil.toList(l.getCoordinate(), RegionDTO.class);
        l.setRegionDTOList(regionDTOS);
      }
    });
    return laborRegionDTOS;
  }

  @Override
  public List<LaborRegionDTO> queryListByTenantId(String tenantId) {
    LobarSet lobarSet = lobarSetService.getByTenantId(tenantId);
    String showArea = lobarSet.getShowArea();
    if(StringUtils.isEmpty(showArea)){
      return null;
    }
    QueryWrapper<LaborRegion> queryWrapper = new QueryWrapper<>();
    List<Integer> list = Arrays.asList(showArea.split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
//    List<Integer> list = new ArrayList<>();
//    list.add(1);list.add(2);list.add(3);
    queryWrapper.eq("tenant_id_",tenantId).in("type_",list);
    List<LaborRegion> laborRegions = baseMapper.selectList(queryWrapper);
    List<LaborRegionDTO> laborRegionDTOS = BeanUtil.copyToList(laborRegions, LaborRegionDTO.class);
    laborRegionDTOS.forEach(l->{
      if (StringUtils.isNotBlank(l.getCoordinate())){
        List<RegionDTO> regionDTOS = JSONUtil.toList(l.getCoordinate(), RegionDTO.class);
        l.setRegionDTOList(regionDTOS);
      }
    });
    return laborRegionDTOS;
  }



  /**
   * 从es获取5分钟内的坐标数据
   * @return
   * @throws IOException
   */
  private List<UserRegionDTO> getUserRegionFromEs() throws IOException {
    RestHighLevelClient rhlClient = eSconfig.getRHLClient();
    SearchRequest request = new SearchRequest(this.laborRegion);
    // 指定检索条件
    Calendar instance = Calendar.getInstance();
    instance.add(Calendar.MINUTE,-5);
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    boolQueryBuilder.must(QueryBuilders.termQuery("tenantId", linkappUserContextProducer.getNotNullCurrent().getTenantId()))
        .must(QueryBuilders.rangeQuery("time").gte(instance.getTimeInMillis()));
    SearchSourceBuilder builder = new SearchSourceBuilder();
    builder.query(boolQueryBuilder).sort("time", SortOrder.DESC);
    request.source(builder);
    // 3、发送请求到ES
    SearchResponse response = rhlClient.search(request, RequestOptions.DEFAULT);
    // 4、处理响应结果
    List<UserRegionDTO> userRegionDTOS = new ArrayList<>();
    for (SearchHit hit : response.getHits().getHits()) {
      UserRegionDTO userRegionDTO = JSONObject.parseObject(hit.getSourceAsString(), UserRegionDTO.class);
      //判断是否已经包含
      long count = userRegionDTOS.stream()
          .filter(u -> u.getUserId().equals(userRegionDTO.getUserId())).count();
      if (count < 1){
        userRegionDTOS.add(userRegionDTO);
      }
    }
    return userRegionDTOS;
  }

  @Override
  public IPage<LaborRegion> queryListByPage(RequestModel<LaborRegion> requestModel) {
    Page page = requestModel.getPage();
    LaborRegion laborRegion = requestModel.getCustomQueryParams();
    //项目id 过滤
    laborRegion.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    IPage<LaborRegion> laborRegionIPage = baseMapper.queryListByPage(page, laborRegion);
    return laborRegionIPage;
  }

  /**
   * 验证重复
   */
  private void checkExist(LaborRegion laborRegion) {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    QueryWrapper<LaborRegion> queryWrapper = new QueryWrapper<>();
    //设置判断重复条件
    queryWrapper.eq("name_",laborRegion.getName())
        .eq("tenant_id_",tenantId);
    //编辑的时候存在id
    Optional.ofNullable(laborRegion.getId()).ifPresent(id -> queryWrapper.ne("id",laborRegion.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("该区域坐标已存在");
    }
  }

  /**
   * 设置基本属性
   * @param laborRegion
   */
  private void setBase(LaborRegion laborRegion) {
    laborRegion.setModifyTime(new Date());
    if(null != linkappUserContextProducer.getCurrent()){
      laborRegion.setModifyId(linkappUserContextProducer.getCurrent().getId());
    }
    //没有id就是新增,有就是编辑
    if (null == laborRegion.getId()){
      if(null != linkappUserContextProducer.getCurrent()){
        laborRegion.setCreatorId(linkappUserContextProducer.getCurrent().getId());
      }
      laborRegion.setCreateTime(new Date());
      if(StringUtils.isBlank(laborRegion.getTenantId())){
        laborRegion.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
      }
    }
  }
}
